<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="85px">
      <el-form-item label="短信签名" prop="signature">
        <el-input
          v-model="queryParams.signature"
          placeholder="请输入短信签名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="模板名称" prop="tmplName">
        <el-input
          v-model="queryParams.tmplName"
          placeholder="请输入模板名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="服务商模板" prop="providerTmplCode">
        <el-input
          v-model="queryParams.providerTmplCode"
          placeholder="请输入服务商模板编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="业务类型" prop="bizCode">
        <el-select v-model="queryParams.bizCode" placeholder="请选择业务类型" clearable>
          <el-option
            v-for="dict in bizList"
            :key="dict.bizCode"
            :label="dict.bizName"
            :value="dict.bizCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="短信类型" prop="tmplType">
        <el-select v-model="queryParams.tmplType" placeholder="请选择短信类型" clearable>
          <el-option
            v-for="dict in dict.type.cms_sms_tmpl_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否启用" prop="isEnable">
        <el-select v-model="queryParams.isEnable" placeholder="请选择是否启用" clearable>
          <el-option
            v-for="dict in dict.type.sys_is_enable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['sms:template:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['sms:template:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['sms:template:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['sms:template:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="templateList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="渠道编码" align="center" prop="channelCode" />
      <el-table-column label="短信签名" align="center" prop="signature" :show-overflow-tooltip=true />
      <el-table-column label="模板名称" align="center" prop="tmplName" />
      <el-table-column label="模板类型" align="center" prop="tmplType" >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.cms_sms_tmpl_type" :value="scope.row.tmplType"/>
        </template>
      </el-table-column>
      <el-table-column label="服务商模板编号" align="center" prop="providerTmplCode" />
      <el-table-column label="短信业务编码" align="center" prop="bizCode" />
      <el-table-column label="短信模板" align="center" prop="tmplContent" :show-overflow-tooltip=true />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="是否启用" align="center" prop="isEnable">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_is_enable" :value="scope.row.isEnable"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['sms:template:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['sms:template:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改短信模板对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="短信类型" prop="tmplType">
              <el-select v-model="form.tmplType" placeholder="请选择短信类型" clearable>
                <el-option
                  v-for="dict in dict.type.cms_sms_tmpl_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="短信签名" prop="signature">
              <el-input v-model="form.signature" placeholder="请输入短信签名" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="短信业务" prop="bizCode">
              <el-select v-model="form.bizCode" placeholder="请选择短信业务" clearable>
                <el-option
                  v-for="dict in bizList"
                  :key="dict.bizCode"
                  :label="dict.bizName"
                  :value="dict.bizCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否启用" prop="isEnable">
              <el-select v-model="form.isEnable" placeholder="请选择是否启用">
                <el-option
                  v-for="dict in dict.type.sys_is_enable"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="模板名称" prop="tmplName">
          <el-input v-model="form.tmplName" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="服务商模板编号" prop="providerTmplCode">
          <el-input v-model="form.providerTmplCode" placeholder="请输入短信服务商模板编号" />
        </el-form-item>


        <el-form-item label="短信模板">
          <el-input
            type="textarea"
            :rows="2"
            placeholder="请输入短信模板内容"
            v-model="form.tmplContent">
          </el-input>
        </el-form-item>
        <el-form-item label="参数数组" prop="tmplParams" v-if="tmplParams.length > 0">
          <el-row v-for="(item , idx) in tmplParams" :key="idx" style="margin-bottom: 5px">
            <el-col :span="11">
              <el-form-item label="参数名：" >
                <el-input v-model="tmplParamsArr[parseInt(idx)].code"  disabled />
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="参数描述：" >
                <el-input v-model="tmplParamsArr[parseInt(idx)].desp" placeholder="请输入参数描述" />
              </el-form-item>
            </el-col>
          </el-row>

        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTemplate, getTemplate, delTemplate, addTemplate, updateTemplate } from "@/api/cms/sms/template";
import {listBizAll} from "@/api/cms/sms/biz"
import { isExternal } from '@/utils/validate'
export default {
  name: "Template",
  dicts: ['sys_is_enable','cms_sms_tmpl_type'],
  props: {
    channelCode: {
      type: String
    }
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 短信模板表格数据
      templateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        channelCode: this.channelCode,
        signature: null,
        tmplType: null,
        tmplName: null,
        providerTmplCode: null,
        bizCode: null,
        isEnable: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        channelCode: [
          { required: true, message: "短信渠道编码不能为空", trigger: "blur" }
        ],
        tmplName: [
          { required: true, message: "模板名称不能为空", trigger: "blur" }
        ],
        providerTmplCode: [
          { required: true, message: "短信服务商模板编号不能为空", trigger: "blur" }
        ],
        bizCode: [
          { required: true, message: "短信业务编码不能为空", trigger: "blur" }
        ],
        tmplContent: [
          { required: true, message: "短信模板内容不能为空", trigger: "blur" }
        ],
        isEnable: [
          { required: true, message: "是否启用  0 否  1 是不能为空", trigger: "change" }
        ],
      },
      bizList: [],
      tmplParamsArr: []
    };
  },

  computed: {

    tmplParams() {
      console.log('来计算');
      var reg = /\$\{(.+?)\}/g;
      var list = [];
      var result = null;
      do {
        result = reg.exec(this.form.tmplContent);
        if (result){
          let obj = {
            code: result[1],
            desp: this.loadDesp(result[1])
          }
          list.push(obj)
        }
      } while (result)
      console.log(list)
      this.tmplParamsArr = [...list]
      return list;
    },
  },
  created() {
    this._listBizAll();
    this.getList();
  },
  methods: {
    loadDesp(code){
      let lnt = this.tmplParamsArr.length;
      if (lnt>0){
        for (let i = 0 ;i< lnt ;i++){
          let item = this.tmplParamsArr[i];
          if (item.code == code){
            return item.desp
          }
        }
      }
      return  "";
    },
    _listBizAll(){
      listBizAll().then(response => {
        this.bizList = response.data;
      });
    },
    /** 查询短信模板列表 */
    getList() {
      this.loading = true;
      listTemplate(this.queryParams).then(response => {
        this.templateList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        channelCode: this.channelCode,
        signature: null,
        tmplType: null,
        tmplName: null,
        providerTmplCode: null,
        bizCode: null,
        tmplContent: null,
        tmplParams: null,
        remark: null,
        isEnable: null,
        createTime: null,
        updateTime: null,
        createBy: null,
        updateBy: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加短信模板";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getTemplate(id).then(response => {
        this.form = response.data;
        if (this.form.tmplParams){
          this.tmplParamsArr = eval(this.form.tmplParams)
        }
        this.open = true;
        this.title = "修改短信模板";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          console.log(JSON.stringify(this.tmplParamsArr))
          this.form.tmplParams = JSON.stringify(this.tmplParamsArr)
          if (this.form.id != null) {
            updateTemplate(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTemplate(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除短信模板编号为"' + ids + '"的数据项？').then(function() {
        return delTemplate(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('sms/template/export', {
        ...this.queryParams
      }, `template_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
